# @Version : 1.0
# @Author  : wxz
# @File    : access_token_middleware.py
# @Time    : 2025/5/29 21:14
# @Describe: 描述...
import time

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse

from commons.access_token_verify import AccessTokenVerify
from config import app_settings

class AccessTokenMiddleware(BaseHTTPMiddleware):
    """
    校验 JWT Token的中间件
    """

    # 不需要访问令牌的URL
    no_access_token_urls = app_settings.no_access_token_urls

    async def dispatch(self, request, call_next):

        # 请求路径
        path = request.url.path

        # 如果请求路径需要Token令牌，则进行Token验证
        if path not in self.no_access_token_urls:
            # 从Header请求头中获取token
            authorization = request.headers.get("Authorization")
            # 校验Token
            resp = await AccessTokenVerify.verify_access_token(authorization)
            if isinstance(resp, JSONResponse):
                return resp
            # # 将用户ID存放到Request对象的state中
            request.state.user_id = resp

        # 放行，继续向下执行
        return await call_next(request)
















